package com.vertxsample.samples.testconsulclient

import com.vertxsample.samples.core.db.HikariPoolUtil
import com.vertxsample.samples.core.web.RequestContext
import com.vertxsample.samples.testconsulclient.controller.JsonController
import com.zaxxer.hikari.HikariConfig
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.Router
import org.slf4j.LoggerFactory

class StarterVerticle(val options :JsonObject) : AbstractVerticle() {
    val logger = LoggerFactory.getLogger(this::class.java)

    override fun start(startFuture: Future<Void>) {




        //启动web
        startServer(startFuture ,options);




    }

    fun  startServer(startFuture:Future<Void>,options :JsonObject){
        var router = customRouter(vertx,options)
        println("server running on 8888")
        vertx.createHttpServer().requestHandler({ handler -> router.handle(handler)}).listen(8888){ result ->
            if (result.succeeded()) {
                startFuture.complete()
            } else {
                startFuture.fail(result.cause())
            }
        }
    }

    fun customRouter(vertx : Vertx,options :JsonObject) : Router {


        //数据配置
        val config = HikariConfig()


        config.jdbcUrl =options.getString("datasource.url")
        config.username = options.getString("datasource.username")
        config.password = options.getString("datasource.password")
        config.driverClassName = options.getString("datasource.driver-class-name")

        config.addDataSourceProperty("cachePrepStmts", "true")
        config.addDataSourceProperty("prepStmtCacheSize", "250")
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")

        val dslContext= HikariPoolUtil.getContext(HikariPoolUtil.getConnection(HikariPoolUtil.getDataSource(config))!!)

        var router = Router.router(vertx)

        router.route("/json").handler({c ->

            JsonController(RequestContext(vertx, c, dslContext)).toJson().thenAccept {
                    it-> c.response().json().end(it)
            }

        })
        return router
    }


    fun HttpServerResponse.json() : HttpServerResponse {
        return this.putHeader("content-type","application/json; charset=utf-8")
    }
}